﻿Imports DTO
Imports System.ComponentModel
Imports System.Threading
Imports BUS
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraPrinting.Preview

Public Class ucPhieuBanHang

    Private dsKH As List(Of KhachHangDTO)
    Private _load As Boolean = False
    Private maPhieu As String
    Private dsNhanVien As DataTable
    Private dsDieuKhoan As List(Of DieuKhoanTTDTO)
    Private hinhThucTT As List(Of HinhThucTTDTO)
    Private dsKhoHang As DataTable
    Private dsChiTiet As BindingList(Of ChiTietBanHangDTO)
    Private dsHangHoa As List(Of HangHoaBanHangDTO)
    Private dtChiTietHH As DataTable
    Private chiecKhau As Double
    Private tienChiecKhau As Double
    Private tienThueVat As Double
    Private phieuBH As PBanHangDTO
    Private pq As New PhanQuyenNhonNDDTO
    Private xuatBaoCao As Thread
    Private maDH As String
    Private dsChiTietDHTrenGrid As BindingList(Of HangHoaGird)
    Private phantramchieckhau As Double = 0


    Private Sub ucPhieuBanHang_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        loadDSKH()
        loadMaPhieu()
        loadDSNhanVien()
        loadDieuKhoanTT()
        LoadHinhThuc()
        loadThongTinNgay()
        loadDSHangHoa()
        addDatasourceDataGrid()
        loadDSKhoHang()
        calcEdVatDonHang.EditValue = 10

        cbbNhanVienLap.EditValue = NhanVienBUS.LayMaNVBangMaND(frmMain.maND)
        cbbTenKH.EditValue = dsKH(0).MaKhachHang
        CalcEdTienChiecKhauDH.EditValue = 0
        CalcEdTienVATDH.EditValue = 0
        gridPhieuHang.AddNewRow()
        calcEdPhanTramCkDonHang.EditValue = chiecKhau
        ckedIn.Checked = True
        _load = True
    End Sub

    Private Sub loadDSKH()
        dsKH = KhachHangBUS.layDanhSachKHTenVaMa()
        cbbTenKH.Properties.DataSource = dsKH
        cbbTenKH.Properties.DisplayMember = "TenKhachHang"
        cbbTenKH.Properties.ValueMember = "MaKhachHang"

        cbbMaKh.Properties.DataSource = dsKH
        cbbMaKh.Properties.DisplayMember = "MaKhachHang"
        cbbMaKh.Properties.ValueMember = "MaKhachHang"
    End Sub

    Private Sub loadMaPhieu()
        maPhieu = PhieuBanHangBUS.layMaPhieu()
        txtPhieu.Text = maPhieu
    End Sub

    Private Sub loadDSNhanVien()
        dsNhanVien = NhanVienBUS.LayDSNhanVienCBX()
        cbbNhanVienLap.Properties.DataSource = dsNhanVien
        cbbNhanVienLap.Properties.DisplayMember = "TenNhanVien"
        cbbNhanVienLap.Properties.ValueMember = "MaNhanVien"
        'cbbNhanVienLap.EditValue = dsNhanVien(0)("MaNhanVien").ToString
    End Sub

    Private Sub loadDieuKhoanTT()
        dsDieuKhoan = DieuKhoanTTBUS.layDSDieuKhoan()
        cbDieuKienTT.Properties.DataSource = dsDieuKhoan
        cbDieuKienTT.Properties.ValueMember = "MaDieuKhoan"
        cbDieuKienTT.Properties.DisplayMember = "TenDieuKhoan"
        cbDieuKienTT.EditValue = 1
    End Sub

    Private Sub cbbTenKH_EditValueChanged(sender As Object, e As EventArgs) Handles cbbTenKH.EditValueChanged, cbbMaKh.EditValueChanged
        If _load = True Then
            Dim control As DevExpress.XtraEditors.GridLookUpEdit = DirectCast(sender, DevExpress.XtraEditors.GridLookUpEdit)
            Dim makh As String = ""
            makh = control.EditValue.ToString
            cbbTenKH.EditValue = makh
            cbbMaKh.EditValue = makh
            Dim kh As KhachHangDTO = dsKH.Find(Function(khachHang As KhachHangDTO)
                                                   Return khachHang.MaKhachHang = makh
                                               End Function)
            txtDt.Text = kh.DienThoai
            txtDiaChi.Text = kh.DiaChi
            chiecKhau = kh.ChiecKhau
            calcEdPhanTramCkDonHang.EditValue = chiecKhau
        End If
    End Sub

    Private Sub LoadHinhThuc()
        hinhThucTT = HinhThucTTBUS.layDsHinhThucTT()
        cbbThanhToan.Properties.DataSource = hinhThucTT
        cbbThanhToan.Properties.DisplayMember = "TenThanhToan"
        cbbThanhToan.Properties.ValueMember = "MaThanhToan"
        cbbThanhToan.EditValue = hinhThucTT(0).MaThanhToan

    End Sub

    Private Sub loadThongTinNgay()
        Dim dateNow As Date = Date.Now
        dateLapPhieu.EditValue = dateNow
        dateGiao.EditValue = dateNow
        dateThanhToan.EditValue = dateNow
    End Sub


    Private Sub loadDSHangHoa()
        dsHangHoa = HangHoaBUS.layDSHangHoaBanHang()
        gridMaHangHoa.DataSource = dsHangHoa
        gridMaHangHoa.DisplayMember = "MaHangHoa"
        gridMaHangHoa.ValueMember = "STT"


        gridTenHangHoa.DataSource = dsHangHoa
        gridTenHangHoa.DisplayMember = "TenHangHoa"
        gridTenHangHoa.ValueMember = "STT"


    End Sub

    Private Sub addDatasourceDataGrid()
        dsChiTietDHTrenGrid = New BindingList(Of HangHoaGird)
        grdCtrlPhieuBan.DataSource = dsChiTietDHTrenGrid
    End Sub

    Private Sub loadDSKhoHang()
        dsKhoHang = KhoHangBUS.LoadBangKhoHang()
        griKhoHangHoa.DataSource = dsKhoHang
        griKhoHangHoa.ValueMember = "MaKhoHang"
        griKhoHangHoa.DisplayMember = "TenKhoHang"
    End Sub

    Private Sub gridPhieuHang_ValidateRow(sender As Object, e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles gridPhieuHang.ValidateRow

        Try
            Dim View As GridView = CType(sender, GridView)
            Dim maHangCol As GridColumn = View.Columns("MaHang")
            Dim maHang As String = ""
            maHang = CType(View.GetRowCellValue(e.RowHandle, colMaHang), String)
            Dim soluongCol As GridColumn = View.Columns("SoLuong")
            Dim sl As Integer = CType(View.GetRowCellValue(e.RowHandle, "SoLuong"), Integer)
            If maHang = "" Then
                e.Valid = False
                'Set errors with specific descriptions for the columns
                View.SetColumnError(maHangCol, "Mã hàng không được để trống")
            End If

            ' If gri Then
            If Not View.GetRowCellValue(e.RowHandle, colMaHang) Is Nothing Then
                Dim stt As Integer = Integer.Parse(View.GetRowCellValue(e.RowHandle, colMaHang).ToString)
                Dim hh As HangHoaBanHangDTO = dsHangHoa.Find(Function(hanghoa As HangHoaBanHangDTO)
                                                                 Return hanghoa.STT = stt
                                                             End Function)

                If sl > hh.SoLuongTon Then
                    e.Valid = False
                    View.SetColumnError(soluongCol, "Số lượng tồn chỉ còn lại " + hh.SoLuongTon.ToString + " sản phẩm")
                End If
            End If
            If Not View.GetRowCellValue(e.RowHandle, colKhoHang) Is Nothing Then
                Dim maKho As String = View.GetRowCellValue(e.RowHandle, colKhoHang).ToString
                Dim stt As Integer = Integer.Parse(View.GetRowCellValue(e.RowHandle, colMaHang).ToString)
                Dim hh As HangHoaBanHangDTO = dsHangHoa.Find(Function(hanghoa As HangHoaBanHangDTO)
                                                                 Return hanghoa.STT = stt
                                                             End Function)
                If maKho <> hh.MaKhoHang Then
                    e.Valid = False
                    View.SetColumnError(colKhoHang, "Sản phẩm không có trong kho này")
                End If
            End If

           

            ' End If

        Catch ex As Exception

        End Try
    End Sub


    Private Sub gridPhieuHang_InvalidRowException(sender As Object, e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles gridPhieuHang.InvalidRowException
        e.ExceptionMode = ExceptionMode.NoAction
    End Sub

    Private Sub gridPhieuHang_CellValueChanging(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gridPhieuHang.CellValueChanging
        Dim index As Integer = gridPhieuHang.GetVisibleIndex(e.RowHandle)
        If e.Column.FieldName = colMaHang.FieldName Or e.Column.FieldName = colTenHang.FieldName Then
            If index = dsChiTietDHTrenGrid.Count Then
                gridPhieuHang.AddNewRow()
            End If

            Dim hangHoa As HangHoaBanHangDTO = dsHangHoa.Find(Function(hh As HangHoaBanHangDTO)
                                                                  Return hh.STT = Integer.Parse(e.Value.ToString)
                                                              End Function)
            dsChiTietDHTrenGrid(index).MaHang = hangHoa.STT.ToString
            dsChiTietDHTrenGrid(index).TenHang = hangHoa.STT.ToString
            dsChiTietDHTrenGrid(index).MaKho = hangHoa.MaKhoHang
            dsChiTietDHTrenGrid(index).DonVi = hangHoa.TenDonVi
            dsChiTietDHTrenGrid(index).ck = chiecKhau
            dsChiTietDHTrenGrid(index).SoLuong = 1
            dsChiTietDHTrenGrid(index).DonGia = hangHoa.GiaBanLe
            'tinhTienCua1SanPham(index)
        End If
        Try
            If e.Column.FieldName = Colsoluong.FieldName Or e.Column.FieldName = colDonGia.FieldName Then
                dsChiTietDHTrenGrid(index).SoLuong = Integer.Parse(e.Value.ToString)
            End If
            If e.Column.FieldName = colDonGia.FieldName Then
                dsChiTietDHTrenGrid(index).DonGia = Double.Parse(e.Value.ToString)
            End If
        Catch ex As Exception

        End Try
       
        tinhTienCua1SanPham(index)
        'tinhTienToanBoDonHang()
    End Sub

    Public Sub tinhTienToanBoDonHang()
        gridPhieuHang.CloseEditor()
        gridPhieuHang.UpdateCurrentRow()
        Dim tongDH As Double = 0
        For Each hh As HangHoaGird In dsChiTietDHTrenGrid
            tongDH += hh.ThanhToan
        Next

        Dim tienVat, tienChiecKhau As Double
        tienChiecKhau = phantramchieckhau * tongDH * 0.01
        CalcEdTienChiecKhauDH.EditValue = tienChiecKhau
        tienVat = Double.Parse(calcEdVatDonHang.EditValue.ToString) * tongDH * 0.01
        CalcEdTienVATDH.EditValue = tienVat
        CalcEdThanhTienDH.EditValue = (tongDH + tienVat) - tienChiecKhau

    End Sub

    Public Sub tinhTienCua1SanPham(index As Integer)
        dsChiTietDHTrenGrid(index).ThanhTien = dsChiTietDHTrenGrid(index).SoLuong * dsChiTietDHTrenGrid(index).DonGia

        dsChiTietDHTrenGrid(index).ChietKhau = dsChiTietDHTrenGrid(index).ThanhTien * (dsChiTietDHTrenGrid(index).ck * 0.01)
        dsChiTietDHTrenGrid(index).ThanhToan = dsChiTietDHTrenGrid(index).ThanhTien - dsChiTietDHTrenGrid(index).ChietKhau

    End Sub

    Private Sub gridPhieuHang_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gridPhieuHang.CellValueChanged
        grdCtrlPhieuBan.DataSource = dsChiTietDHTrenGrid
        tinhTienToanBoDonHang()
    End Sub


    Private Sub calcEdPhanTramCkDonHang_EditValueChanged(sender As Object, e As EventArgs) Handles calcEdPhanTramCkDonHang.EditValueChanged, calcEdVatDonHang.EditValueChanged
        If _load = True Then
            phantramchieckhau = DirectCast(calcEdPhanTramCkDonHang.EditValue, Double)
            tinhTienToanBoDonHang()
        End If

    End Sub

    Private Sub btnTaoMoi_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnTaoMoi.ItemClick
        dsChiTietDHTrenGrid.Clear()
        txtDiaChi.Text = ""
        txtGhiChu.Text = ""
        txtDt.Text = ""
        loadMaPhieu()
    End Sub

    Private Sub btnLuu_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnLuu.ItemClick
        Dim pq As PhanQuyenNhonNDDTO = ChucNangBUS.layQuyenCuaND(frmMain.maND, 31)
        If pq.Them = True Then
            gridPhieuHang.CloseEditor()
            gridPhieuHang.UpdateCurrentRow()
            If kiemtraluu() = True Then
                Dim tongDH As Double = 0

                tinhTienToanBoDonHang()
                dsChiTiet = New BindingList(Of ChiTietBanHangDTO)
                For Each hangHoa As HangHoaGird In dsChiTietDHTrenGrid
                    Dim maHH As String = dsHangHoa.Find(Function(hh As HangHoaBanHangDTO)
                                                            Return hh.STT = Integer.Parse(hangHoa.MaHang)
                                                        End Function).MaHangHoa
                    Dim ct As New ChiTietBanHangDTO
                    ct.MaHang = maHH
                    ct.MaKho = hangHoa.MaKho
                    ct.SoLuong = hangHoa.SoLuong
                    ct.DonGia = hangHoa.DonGia
                    ct.ThanhTien = hangHoa.ThanhTien
                    ct.ChietKhau = hangHoa.ChietKhau
                    ct.ThanhToan = hangHoa.ThanhToan
                    tongDH += ct.ThanhToan
                    dsChiTiet.Add(ct)
                Next
                phieuBH = New PBanHangDTO
                phieuBH.MaKhachHang = cbbMaKh.EditValue.ToString
                phieuBH.Ngay = Date.Parse(dateLapPhieu.EditValue.ToString)
                phieuBH.MaNhanVien = cbbNhanVienLap.EditValue.ToString
                phieuBH.NgayGiao = Date.Parse(dateGiao.EditValue.ToString)
                phieuBH.MaHinhThuc = Integer.Parse(cbbThanhToan.EditValue.ToString)
                phieuBH.MaDieuKhoan = Integer.Parse(cbDieuKienTT.EditValue.ToString)
                phieuBH.HanThanhToan = Date.Parse(dateThanhToan.EditValue.ToString)
                phieuBH.ChietKhau = Double.Parse(calcEdPhanTramCkDonHang.EditValue.ToString)
                phieuBH.VAT = Double.Parse(calcEdVatDonHang.EditValue.ToString)
                phieuBH.TongDonHang = tongDH
                phieuBH.GhiChu = txtGhiChu.Text
                maDH = PBanHangBUS.themDonHang(phieuBH)
                Dim kq As Integer = PBanHangBUS.themChiTietDH(dsChiTiet, maDH)
                If kq = dsChiTiet.Count Then
                    DevExpress.XtraEditors.XtraMessageBox.Show("Thêm đơn hàng thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    HeThongBUS.themNhatKy(frmMain.maND, "Bán Hàng", "Thêm đơn hàng", frmMain.maND + " thêm đơn hàng " + maPhieu)
                    If pq.InPQ = False Then
                        DevExpress.XtraEditors.XtraMessageBox.Show("Bạn không có quyền in", "Lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
                    Else
                        If (DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muôn in phiếu xuất hàng", "Thông Báo", _
              MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                            xuatPhieu(maDH)
                        End If


                    End If
                    dsChiTietDHTrenGrid.Clear()
                    txtDiaChi.Text = ""
                    txtGhiChu.Text = ""
                    txtDt.Text = ""
                    loadMaPhieu()
                End If
            End If
        Else
            DevExpress.XtraEditors.XtraMessageBox.Show("Bạn chưa thêm đơn hàng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Sub
    Private Function kiemtraluu() As Boolean
        If cbbTenKH.EditValue Is Nothing Or cbbMaKh.EditValue Is Nothing Then
            DevExpress.XtraEditors.XtraMessageBox.Show("Bạn chưa chọn khách hàng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End If
        If dsChiTietDHTrenGrid.Count <= 0 Then
            DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có sản phẩm nào trong đơn hàng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End If
        Return True
    End Function

    Private Sub xuatPhieu(maDH As String)
        Dim dt As New DataTable()
        dt = BaoCaoBUS.layPhieuBanHang(maDH)
        Dim rep As New PhieuXuatHang
        rep.BeginUpdate()
        rep.DataSource = dt
        rep.EndUpdate()
        rep.CreateDocument()

        Dim form As New PrintPreviewFormEx()
        form.Text = "Xem trước khi in"
        form.PrintingSystem = rep.PrintingSystem
        form.ShowDialog()
    End Sub


    Private Sub gridPhieuHang_KeyDown(sender As Object, e As KeyEventArgs) Handles gridPhieuHang.KeyDown
        If (e.KeyCode = Keys.Delete) Then
            If (DevExpress.XtraEditors.XtraMessageBox.Show("Delete row?", "Confirmation", _
              MessageBoxButtons.YesNo) <> DialogResult.Yes) Then Return
            dsChiTietDHTrenGrid.RemoveAt(gridPhieuHang.FocusedRowHandle)
            'grdCtrlPhieuBan.DataSource = dtChiTietHH
            tinhTienToanBoDonHang()
        End If
    End Sub

    Private Sub gridPhieuHang_CustomDrawRowIndicator(sender As Object, e As RowIndicatorCustomDrawEventArgs) Handles gridPhieuHang.CustomDrawRowIndicator
        If e.RowHandle >= 0 Then
            If e.Info.IsRowIndicator Then
                e.Info.DisplayText = (e.RowHandle + 1).ToString()
            End If
        End If
    End Sub

    Private Sub btnNapLai_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnNapLai.ItemClick
        grdCtrlPhieuBan.DataSource = dsChiTietDHTrenGrid
        tinhTienToanBoDonHang()
    End Sub
End Class

Public Class HangHoaGird

    Public Property MaHang As String
    Public Property TenHang As String
    Public Property MaKho As String
    Public Property DonVi As String
    Public Property SoLuong As Double
    Public Property DonGia As Double
    Public Property ThanhTien As Double
    Public Property ck As Double
    Public Property ChietKhau As Double
    Public Property ThanhToan As Double
End Class
